const express = require("express");
const mongoose = require("mongoose");
const md5 = require("md5");
const jwt = require("jsonwebtoken");
const router = express.Router();

async function dbMain() {
	try {
		await mongoose.connect("mongodb://localhost:27017/event");
	} catch (err) {
		console.log(err);
	}
}
dbMain();

const eventSchema = new mongoose.Schema({
	eventname: {
		type: String,
		required: [true, "事件不能为空"],
	},
	eventtime: {
		type: Date,
	},
	eventmoney: {
		type: Number,
	},
	eventnote: {
		type: String,
	},
	eventtype: {
		type: String,
	},
});
const userSchema = new mongoose.Schema({
	nickname: {
		type: String,
		required: [true, "请取一个名字"],
	},
	userID: {
		type: Number,
		required: [true, "请设定账户"],
	},
	userPwd: {
		type: String,
	},
	userEmail: {
		type: String,
	},
});

const event = mongoose.model("event", eventSchema);
const user = mongoose.model("user", userSchema);


//发送列表
router.post("/create", async (req, res) => {
	try {
		const rawdata = req.body;
		await event.create(rawdata);
		const baseUrl = `${req.protocol}://${req.get("host")}`;
		const redirectUrl = new URL("/okAlert.html", baseUrl).href;
		res.redirect(redirectUrl);
	} catch (err) {
		res.json({
			code: "1001",
			msg: "创建失败",
			data: err,
		});
	}
});

//获取列表
router.get("/event", async (req, res) => {
  try {
    // 1. 从请求头获取 Authorization
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1]; // 获取 Bearer 后的 token

    // 2. 检查 token 是否存在
    if (!token) {
      return res.status(401).json({
        code: "4001",
        msg: "未提供访问令牌，请先登录",
        data: null
      });
    }

    // 3. 验证 token 是否有效
    let decoded;
    try {
      decoded = jwt.verify(token, "DingyuxiangJIZHANGBENlianxi");
    } catch (err) {
      // token 无效或过期
      return res.status(403).json({
        code: "4002",
        msg: "令牌无效或已过期，请重新登录",
        data: null
      });
    }

    // ✅ 验证通过！你可以使用 decoded 中的用户信息（如 decoded.userID）
    console.log('当前用户:', decoded);

    // 4. 查询事件数据（可选：后续可加上 .where({ userID: decoded.userID }) 实现个人数据隔离）
    const rawdata = await event.find().sort({ eventtime: -1 }).exec(); // 注意：字段是 eventtime，不是 time

    res.json({
      code: "0000",
      msg: "获取成功",
      data: rawdata,
    });
  } catch (err) {
    console.error('获取事件列表出错:', err);
    res.status(500).json({
      code: "1000",
      msg: "服务器内部错误",
      data: null,
    });
  }
});

//删除数据
router.delete("/event/:id", async (req, res) => {
	try {
		const id = req.params.id;
		await event.deleteOne({ _id: id });
		res.json({
			code: "0000",
			msg: "删除成功",
			data: {},
		});
	} catch (err) {
		res.json({
			code: "1002",
			msg: "删除失败",
			data: err,
		});
	}
});

//获取单条数据
router.get("/event/:id", async (req, res) => {
	try {
		const id = req.params.id;
		await event.findById({ _id: id });
		res.json({
			code: "0000",
			msg: "获取成功",
			data: {},
		});
	} catch (err) {
		res.json({
			code: "1003",
			msg: "获取失败",
			data: err,
		});
	}
});

//更新
router.patch("/event/:id", async (req, res) => {
	try {
		let id = req.params.id;
		await event.updateOne({ _id: id }, req.body);
		res.json({
			code: "0000",
			msg: "更新成功",
			data: {},
		});
	} catch (err) {
		res.json({
			code: "1004",
			msg: "更新失败",
			data: err,
		});
	}
});

// router.goReg("/goReg",(req,res)=>{
// 	try{
// 		res.sendFile()
// 	}catch(err){
// 		res.json({
// 			code: "1005",
// 			msg: "跳转失败",
// 			data: err,
// 		});
// 	}
// })

//注册
router.post("/register", async (req, res) => {
	try {
		const rawdata = req.body;
		if (rawdata.userPwd) {
			rawdata.userPwd = md5(rawdata.userPwd);
		} else {
			throw new Error("密码不能为空");
		}

		await user.create(rawdata);
		const baseUrl = `${req.protocol}://${req.get("host")}`;
		const redirectUrl = new URL("/okAlert.html", baseUrl).href;
		res.redirect(redirectUrl);
	} catch (err) {
		res.json({
			code: "1006",
			msg: "注册失败",
			data: err,
		});
	}
});

//登录
router.post("/login", async (req, res) => {
	try {
		let { userID, userPwd, nickname } = req.body;
		let result = await user.findOne({ userID: userID, userPwd: md5(userPwd) });
		if (result === null) {
			throw new Error("用户不存在或密码错误");
		} else {
			let token = jwt.sign(
				{
					username: nickname,
					userID: userID,
				},
				"DingyuxiangJIZHANGBENlianxi",
				{
					expiresIn: 60 * 60 * 24,
				}
			);
			// const baseUrl = `${req.protocol}://${req.get("host")}`;
			// const redirectUrl = new URL("/okAlert.html", baseUrl).href;
			// res.redirect(redirectUrl);
			res.json({
				code: "0000",
				msg: "ok",
				data: token,
			});
		}
	} catch (err) {
		res.json({
			code: "1007",
			msg: err.message,
			data: err,
		});
	}
});

//退出登录
// router.get("/loginOut", async (req, res) => {
// 	req.session.destroy(() => {
// 		res.send("ok");
// 	});
// });
module.exports = router;
